package cn.wolfcode.web.controller;

import cn.wolfcode.domain.User;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.qo.UserQuery;
import cn.wolfcode.service.IUserService;
import cn.wolfcode.utils.TokenManager;
import cn.wolfcode.vo.JsonResult;
import cn.wolfcode.vo.LoginInfo;
import cn.wolfcode.vo.Page;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import cn.wolfcode.utils.TokenManager;

@RestController
@RequestMapping("/user")
public class UserController {

    private final IUserService userService;

    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @RequestMapping("/list")
    public JsonResult<Page<User>> query(UserQuery qo) {
        if (qo == null) {
            qo = new UserQuery();
        }
        Page<User> query = userService.query(qo);
        return JsonResult.success(query);
    }
    @RequestMapping("/changeStatus")
    public JsonResult<?> changeStatus(Long id, String status) {
        userService.changeStatus(id, status);
        return JsonResult.success();
    }

    @RequestMapping("/getInfo")
    public JsonResult<LoginInfo> getInfo(@RequestHeader(value = TokenManager.TOKEN_NAME, required = false) String token) {
        // 从请求头中获取 token
       /* 方法1.
            1.参数写上HttpServletRequest req
            2.String token=req.getHeader("X-Token")*/

       //hasLength会有空格,hasText没有空格
        if (!StringUtils.hasText(token)) {
            return JsonResult.failed(400, "token 不能为空");
        }

        LoginInfo info = TokenManager.getInfo(token);
        return JsonResult.success(info);
    }

    @RequestMapping("/saveOrUpdate")
    @ResponseBody//返回json要加这一句,如果整个类的方法 都返回Json 那么在类上面加
    public JsonResult<?> saveOrUpdate(@RequestBody User user) {
        if (user.getId() != null) {
            userService.updateById(user);
        } else {
            userService.save(user);
        }

        return JsonResult.success();
    }

    @RequestMapping("/delete")
    public JsonResult<?> delete(Long id,boolean deleted) {
        if (id == null) {
            return JsonResult.failed("删除的 id 不能为空!");
        }
//        userService.deleteById(id);
        userService.logicDeleteById(id,deleted);
        return JsonResult.success();
    }
}
